<template>
  <nav-bar>
    <template v-slot:default>订单预览</template>
  </nav-bar>

  <div style="margin-top:45px"></div>
  <van-contact-card type="add" add-text="添加地址" @click="goTo" v-if="Object.keys(address).length === 0"/>
  <div class="address van-cell van-contact-card" @click="goTo" v-if="Object.keys(address).length > 0">
    <div class="left">
      <p>{{ address.name }} {{ address.phone }}</p>
      <p>{{ address.province }} {{ address.city }} {{ address.county }} {{ address.address }}</p>
    </div>
    <div class="van-icon van-icon-arrow van-cell__right-icon"></div>
  </div>

  <van-card v-for="item in carts" :key="item.id"
            :num="item.num"
            :thumb="item.goods.cover_url"
            lazy-load
            style="text-align: left"
  >
    <template #title>
      <div class="title">{{ item.goods.title }}</div>
    </template>
    <template #price>
      <div class="price"><small>￥</small>{{ item.goods.price }}.00</div>
    </template>
  </van-card>

  <van-popup
      v-model:show="show"
      closeable
      position="bottom"
      :style="{ height: '30%' }"
      @close="close"
  >
    <van-grid :border="false" :column-num="2" style="margin: 8px;padding: 8px">
      <van-grid-item title="支付宝">
        <div>支付宝二维码</div>
        <van-image :src="aliyun" />
      </van-grid-item>
      <van-grid-item title="微信">
        <div>微信二维码</div>
        <van-image :src="wechat" />
      </van-grid-item>
    </van-grid>
  </van-popup>

  <van-submit-bar :price="total * 100" button-text="生成订单" @submit="onSubmit" :disabled="disabled" style="bottom:50px;">
    商品金额
  </van-submit-bar>
</template>

<script>
import {reactive, toRefs, onMounted, computed} from "vue";
import {useRouter} from "vue-router";
import {useStore} from "vuex";
import {Toast} from "vant";
import {getOrderPreview, payOrder, payOrderStatus} from "network/order"
import NavBar from "components/common/navbar/NavBar";
import {createOrder} from "../../network/order";

export default {
  name: "CreateOrder",
  components: {
    NavBar
  },
  setup() {
    const router = useRouter(),
        store = useStore()

    // 数据模型
    const state = reactive({
      address: {},
      carts: [],
      disabled: false,
      orderNo: '',
      show: false,
      aliyun: '',
      wechat: '',
    })

    // 数据方法
    const init = () => {
      Toast.loading({message: '加载中...', forbidClick: true})
      // 订单预览获取地址信息
      getOrderPreview().then(res => {
        let addresses = res.address.filter(el => el.is_default === 1)
        state.address = addresses.length ? addresses.shift() : {}
        state.carts = res.carts
        Toast.clear()
      })
    }

    // 地址管理
    const goTo = () => router.push({
      name: 'Address',
    })

    // 金额合计
    const total = computed(() => state.carts.reduce((prev, next) => prev + parseInt(next.num) * parseFloat(next.goods.price), 0))

    // 生成订单
    const onSubmit = () => {
      state.disabled = true
      createOrder({address_id: state.address.id}).then(res => {
        Toast('创建定单成功')
        store.commit('addCart', {count: 0})
        // store.dispatch('updateCart')
        state.disabled = false
        state.orderNo = res.id
        state.show = true
        payOrder(state.orderNo, {type: 'aliyun'}).then(res => state.aliyun = res.qr_code_url)
        // payOrder(state.orderNo, {type: 'wechat'}).then(res => state.wechat = res.qr_code_url)
        payOrder(state.orderNo, {type: 'aliyun'}).then(res => state.wechat = res.qr_code_url)
        // 轮询支付状态
        let timer = setInterval(() => {
          payOrderStatus(state.orderNo).then(res => {
            if (res === 2) {
              clearInterval(timer)
              state.show = false
              router.push({
                name: 'OrderDetail',
                query: {id: state.orderNo}
              })
            }
          })
        }, 2000)
      })
    }

    // 关闭弹出层
    const close = () => router.push({
      name: 'OrderDetail',
      query: {id: state.orderNo}
    })

    // 挂载完成
    onMounted(() => {
      init()
    })
    return {
      ...toRefs(state), total, onSubmit, close, goTo
    }
  }
}
</script>

<style scoped lang="scss">
.address {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    text-align: left;
  }
}

.title {
  margin-top: 1rem;
}

.price {
  margin-bottom: 1rem;
  color: red;
}
</style>